<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Demo</title>
    <style>
        h1 {
            font-size: 24px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div>
    <h1>WebSocket Demo</h1>
    <input type="text" id="sendText"/>
    <button id="sendBtn">Send Message</button>
    <p id="responseText"></p>
</div>

<script>
    let socket = null;
    let sendText = document.getElementById('sendText');
    let responseText = document.getElementById('responseText');
    let response = "";

    // 连接WebSocket
    function connectWebSocket() {
        socket = new WebSocket('ws://localhost:8080/ws');

        socket.onopen = function() {
            console.log('WebSocket connected');
        };

        socket.onmessage = function(event) {
            console.log('Received from server:', event.data);
            response += "\n" + event.data;
            // 将换行符 \n 替换为 <br> 标签
            responseText.innerHTML = response.replace(/\n/g, '<br>');
        };

        socket.onerror = function(error) {
            console.error('WebSocket error:', error);
        };

        socket.onclose = function() {
            console.log('WebSocket connection closed');
        };
    }

    // 发送消息
    function sendMessage() {
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(sendText.value);
        }
    }

    // 页面加载时连接 WebSocket
    window.onload = function() {
        connectWebSocket();
    };

    // 页面卸载时关闭 WebSocket
    window.onbeforeunload = function() {
        if (socket) {
            socket.close();
        }
    };

    // 按钮点击事件绑定
    document.getElementById('sendBtn').onclick = sendMessage;
</script>
</body>
</html>
